package com.icebergteam.warfacewidget.core.monet;

import java.math.BigDecimal;
import java.util.Locale;

import com.icebergteam.warfacewidget.core.LogManager;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalPayment;

import android.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

public class SimplePayPalView extends FrameLayout implements OnClickListener {

	// The PayPal server to be used - can also be ENV_NONE and ENV_LIVE
	private static final int SERVER_SANDBOX = PayPal.ENV_SANDBOX;
	// The ID of your application that you received from PayPal live -
	private static final String APPID_SANDBOX = "APP-80W284485P519543T";
	
	private static final int SERVER_LIVE = PayPal.ENV_LIVE;
	private static final String APPID_LIVE = "APP-4CD250454M372790C";

	protected static final int INITIALIZE_SUCCESS = 0;
	protected static final int INITIALIZE_FAILURE = 1;
	
	public static final String className = SimplePayPalView.class.getCanonicalName();

	ProgressBar progressBar;
	TextView info;
	LinearLayout horizontalLayout;
	
	boolean sandboxState = true;
	

	// You will need at least one CheckoutButton, this application has four for
	// examples
	CheckoutButton launchSimplePayment;

	// This handler will allow us to properly update the UI. You cannot touch
	// Views from a non-UI thread.
	Handler hRefresh = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case INITIALIZE_SUCCESS:
				setupButtons();
				break;
			case INITIALIZE_FAILURE:
				showFailure();
				break;
			}
		}
	};
	
	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
	
		if(launchSimplePayment != null){
			initLibrary();
		}
	}
	
	public void showMessageDialog(final String title, final String message) {
		Activity activity = (Activity) this.getContext();
		activity.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						SimplePayPalView.this.getContext());
				builder.setTitle(title);
				builder.setMessage(message);
				builder.setPositiveButton(R.string.ok, null);
				builder.show();
			}
		});
	}

	private void init(){
		setLayoutParams(new LayoutParams(new LayoutParams(
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT)));

		horizontalLayout = new LinearLayout(this.getContext());
		horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);

		progressBar = new ProgressBar(horizontalLayout.getContext());
		
		progressBar.setScaleY((float) 0.5);
		progressBar.setScaleX((float) 0.5);

		info = new TextView(horizontalLayout.getContext());
		info.setLayoutParams(new LayoutParams(
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				android.view.ViewGroup.LayoutParams.MATCH_PARENT));
		info.setGravity(Gravity.CENTER_VERTICAL);

		horizontalLayout.addView(progressBar);
		horizontalLayout.addView(info);

		addView(horizontalLayout);

		// Initialize the library. We'll do it in a separate thread because it
		// requires communication with the server
		// which may take some time depending on the connection strength/speed.
		Thread libraryInitializationThread = new Thread() {
			public void run() {
				initLibrary();

				// The library is initialized so let's create our CheckoutButton
				// and update the UI.
				if (PayPal.getInstance().isLibraryInitialized()) {
					hRefresh.sendEmptyMessage(INITIALIZE_SUCCESS);
				} else {
					hRefresh.sendEmptyMessage(INITIALIZE_FAILURE);
				}
			}
		};
		libraryInitializationThread.start();
	}
	public SimplePayPalView(Context context) {
		super(context);
		this.sandboxState = false;
		init();
	}
	public SimplePayPalView(Context context, boolean sandboxState) {
		super(context);
		this.sandboxState = sandboxState;
		init();
	}

	/**
	 * The initLibrary function takes care of all the basic Library
	 * initialization.
	 * 
	 * @return The return will be true if the initialization was successful and
	 *         false if
	 */
	private void initLibrary() {
		info.setText("Init PayPal button");

		PayPal pp = PayPal.getInstance();
		// If the library is already initialized, then we don't need to
		// initialize it again.
		if (pp == null) {
			// This is the main initialization call that takes in your Context,
			// the Application ID, and the server you would like to connect to.
			if(this.sandboxState){
				pp = PayPal.initWithAppID(this.getContext(), APPID_SANDBOX, SERVER_SANDBOX);
			}
			else{
				pp = PayPal.initWithAppID(this.getContext(), APPID_LIVE, SERVER_LIVE);
			}
			

			// -- These are required settings.
			try {
				pp.setLanguage(Locale.getDefault().toString());
			} catch (Exception e) {
				LogManager.LogE(SimplePayPalView.className, LogManager.getExecuteMethodName(), e.getMessage());
				e.printStackTrace();
			} // Sets the language for the library.
			// --

			// -- These are a few of the optional settings.
			// Sets the fees payer. If there are fees for the transaction, this
			// person will pay for them. Possible values are FEEPAYER_SENDER,
			// FEEPAYER_PRIMARYRECEIVER, FEEPAYER_EACHRECEIVER, and
			// FEEPAYER_SECONDARYONLY.
			pp.setFeesPayer(PayPal.FEEPAYER_EACHRECEIVER);
			// Set to true if the transaction will require shipping.
			pp.setShippingEnabled(true);

			// Dynamic Amount Calculation allows you to set tax and shipping
			// amounts based on the user's shipping address. Shipping must be
			// enabled for Dynamic Amount Calculation. This also requires you to
			// create a class that implements PaymentAdjuster and Serializable.
			pp.setDynamicAmountCalculationEnabled(false);

			// --
		}
	}

	/**
	 * Create our CheckoutButton and update the UI.
	 */
	public void setupButtons() {
		PayPal pp = PayPal.getInstance();
		// Get the CheckoutButton. There are five different sizes. The text on
		// the button can either be of type TEXT_PAY or TEXT_DONATE.
		launchSimplePayment = pp.getCheckoutButton(this.getContext(),
				PayPal.BUTTON_194x37, CheckoutButton.TEXT_DONATE);
		// You'll need to have an OnClickListener for the CheckoutButton. For
		// this application, MPL_Example implements OnClickListener and we
		// have the onClick() method below.
		launchSimplePayment.setOnClickListener(this);
		// The CheckoutButton is an android LinearLayout so we can add it to our
		// display like any other View.
		addView(launchSimplePayment);

		horizontalLayout.setVisibility(View.GONE);

	}

	/**
	 * Show a failure message because initialization failed.
	 */
	public void showFailure() {
		// showMessageDialog("WoT Widget Donate",
		// "FAILURE. Could not initialize the PayPal library.");
		info.setText("Check Internet connection");
		progressBar.setVisibility(View.GONE);
	}

	@Override
	public void onClick(View v) {
		
		/**
		 * For each call to checkout() and preapprove(), we pass in a
		 * ResultDelegate. If you want your application to be notified as soon
		 * as a payment is completed, then you need to create a delegate for
		 * your application. The delegate will need to implement
		 * PayPalResultDelegate and Serializable. See our ResultDelegate for
		 * more details.
		 */

		if (v == launchSimplePayment) {
			// Use our helper function to create the simple payment.
			PayPalPayment payment = exampleSimplePayment();
			launchSimplePayment.updateButton();
			// Use checkout to create our Intent.
			Intent checkoutIntent = PayPal.getInstance().checkout(payment,
					this.getContext(), new ResultDelegate(this));
			// Use the android's startActivityForResult() and pass in our
			// Intent. This will start the library.
			this.getContext().startActivity(checkoutIntent);

		}
	}

	/**
	 * Create a PayPalPayment which is used for simple payments.
	 * 
	 * @return Returns a PayPalPayment.
	 */
	private PayPalPayment exampleSimplePayment() {
		// Create a basic PayPalPayment.
		PayPalPayment payment = new PayPalPayment();
		// Sets the currency type for this payment.
		payment.setCurrencyType("USD");
		// Sets the recipient for the payment. This can also be a phone number.
		payment.setRecipient("szzzs2006@gmail.com");
		// Sets the amount of the payment, not including tax and shipping
		// amounts.
		payment.setSubtotal(new BigDecimal("1.00"));
		// Sets the payment type. This can be PAYMENT_TYPE_GOODS,
		// PAYMENT_TYPE_SERVICE, PAYMENT_TYPE_PERSONAL, or PAYMENT_TYPE_NONE.
		payment.setPaymentType(PayPal.PAY_TYPE_SIMPLE);

		// Sets the merchant name. This is the name of your Application or
		// Company.
		payment.setMerchantName("WoT Widget Donate");

		// Sets the Custom ID. This is any ID that you would like to have
		// associated with the payment.
		payment.setCustomID("8873482296");
		// Sets the Instant Payment Notification url. This url will be hit by
		// the PayPal server upon completion of the payment.
		// payment.setIpnUrl("http://www.exampleapp.com/ipn");

		return payment;
	}

}
